home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 196 < prev    next >
Text File  |  1996-08-06  |  2KB  |  60 lines

  1. Newsgroups: comp.std.c
  2. Path: nntp.coast.net!torn!sq!msb
  3. From: msb@sq.com (Mark Brader)
  4. Subject: Re: integral types in switch expressions
  5. Message-ID: <1996Jan26.220546.22346@sq.com>
  6. Organization: SoftQuad Inc., Toronto, Canada
  7. References: <4eb5r1$b04@news.tuwien.ac.at>
  8. Date: Fri, 26 Jan 1996 22:05:46 GMT
  9.  
  10. Konrad Schwarz (schwarz@mips.complang.tuwien.ac.at) writes:
  11. > I was surprised to learn that constant pointer expressions are
  12. > not allowed in case labels and that the expression in a switch statement
  13. > must be an integral type.  ...
  14. > Consider:
  15. > T a [] = { ... } ...
  16. > switch (c) {
  17. >     case a: ...
  18. >     case a + 1: ...
  19. >     case a + 3: ...
  20. >     default: ...
  21. > }
  22. > where T is some type.
  23.  
  24. I don't know what was in the Committee's minds, but I can point out
  25. that this code contains constant pointer expressions only when a[]
  26. has static storage duration.  Therefore, without extending the switch
  27. statement to support case-expressions that would have to be computed
  28. at run time, you would have a construct that would be useful for some
  29. pointer values but not others.
  30.  
  31. > I am of course aware that
  32. > switch (c - a) {
  33. >     case 0: ...
  34. >     case 1: ...
  35. >     case 3: ...
  36. >     default: ...
  37. > }
  38. > is equivalent code, but it suffers from the division needed to evaluate
  39. > c - a.
  40.  
  41. No, unfortunately, it isn't.  The first one, if it worked at all, would
  42. work for *any* value c of appropriate type.  In the second one, c must
  43. point to an element of a[], or one past the last element.  But the
  44. overhead of division, at least, is a red herring given a suitable
  45. optimizer, as the code can simply be compiled as if it read:
  46.  
  47.   switch ((char *) c - (char *) a) {
  48.       case 0 * sizeof *a: ...
  49.       case 1 * sizeof *a: ...
  50.       case 3 * sizeof *a: ...
  51.       default: ...
  52.   }
  53.  
  54. -- 
  55. Mark Brader, msb@sq.com        "do right; have fun; make money"
  56. SoftQuad Inc., Toronto              -- Ian Darwin on Yuri Rubinski (1952-96)
  57.  
  58. My text in this article is in the public domain.
  59.